/**
 * * Program : GTravelling
 * Written by : Le Xuan Ninh 
 * Email : xuanninh.it@gmail.com
 * Created date: 06/03/2012 
 * Modified by: 
 * Modified date:
 * Version: 1.0
 * Description:
 */
package com.android.gtravelling;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.dto.ProvincesDTO;

public class VietTravel extends Activity {

	private ListView mainListView;
	public static ArrayList<ProvincesDTO> listProvinces;
	private ArrayAdapter<ProvincesDTO> listAdapter;
	private WebserviceCaller WebCaller;
	private EditText filterText = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_province);

		mainListView = (ListView) findViewById(R.id.lv_province);
		WebCaller = new WebserviceCaller();
		listProvinces = WebCaller.selectAllProvinces();
		// ArrayList<ProvincesDTO> sm=listProvinces.
		listAdapter = new ProvincesDTOArrayAdapter(this, listProvinces);
		mainListView.setAdapter(listAdapter);
		mainListView.setTextFilterEnabled(true);
		filterText = (EditText) findViewById(R.id.edt_search);
		filterText.addTextChangedListener(filterTextWatcher);
		mainListView.setFastScrollEnabled(true);

		mainListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int i, long l) {
				try {
					// int poss = mainListView.getse.getSelectedItemPosition();
					int id = listProvinces.get(i).getId();
					Intent is = new Intent(v.getContext(),
							VietTravelActivity.class);
					is.putExtra(Intent.EXTRA_TEXT, String.valueOf(id));
					startActivity(is);
				} catch (Exception e) {
					System.out.println("Nay, cannot get the selected index");
				}
			}
		});
	}

	private TextWatcher filterTextWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			listAdapter.getFilter().filter(filterText.getText().toString());
			listAdapter.notifyDataSetChanged();
		}
	};

	public void displayAMessage(String msg) {
		AlertDialog alertDialog;
		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle("Message");
		alertDialog.setMessage(msg);
		alertDialog.show();
	}

	private class ProvincesDTOViewHolder {
		private ImageView imgView;

		public ImageView getImgView() {
			return imgView;
		}

		public void setImgView(ImageView imgView) {
			this.imgView = imgView;
		}

		private TextView textView;
		private TextView textView1;

		public ProvincesDTOViewHolder() {
		}

		public ProvincesDTOViewHolder(TextView textView) {
			this.textView = textView;
		}

		public ProvincesDTOViewHolder(TextView textView, TextView textView1) {
			this.textView = textView;
			this.textView1 = textView1;
		}

		public ProvincesDTOViewHolder(ImageView imgView, TextView textView,
				TextView textView1) {
			this.imgView = imgView;
			this.textView = textView;
			this.textView1 = textView1;
		}

		public TextView getTextView() {
			return textView;
		}

		public TextView getTextView1() {
			return this.textView1;
		}

		public void setTextView(TextView textView) {
			this.textView = textView;
		}
	}

	private class ProvincesDTOArrayAdapter extends ArrayAdapter<ProvincesDTO>
			implements Filterable {

		private LayoutInflater inflater;
		public ArrayList<ProvincesDTO> lstAllItem;
		public ArrayList<ProvincesDTO> lstSubItem;
		private PTypeFilter filter;

		public ProvincesDTOArrayAdapter(Context context,
				ArrayList<ProvincesDTO> planetList) {
			super(context, R.layout.row_province, R.id.tv_province_title,
					planetList);
			this.lstSubItem = planetList;
			lstAllItem = planetList;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return lstSubItem.size();
		}

		@Override
		public Filter getFilter() {
			if (filter == null) {
				filter = new PTypeFilter();
			}
			return filter;
		}

		private InputStream fetch(String urlString)
				throws MalformedURLException, IOException {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(urlString);
			HttpResponse response = httpClient.execute(request);
			return response.getEntity().getContent();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			// ProvincesDTO prov = (ProvincesDTO) this.getItem(position);
			ProvincesDTO prov = lstSubItem.get(position);
			// The child views in each row.
			ImageView imgView;
			TextView textView;
			TextView textView1;
			// Create a new row view
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.row_province, null);
				// Find the child views.
				imgView = (ImageView) convertView
						.findViewById(R.id.imgRowContent);
				textView = (TextView) convertView
						.findViewById(R.id.tv_province_title);

				textView1 = (TextView) convertView
						.findViewById(R.id.tv_province_Descrip);

				// Optimization: Tag the row with it's child views, so we don't
				// have to
				// call findViewById() later when we reuse the row.
				convertView.setTag(new ProvincesDTOViewHolder(imgView,
						textView, textView1));
			}
			// Reuse existing row view
			else {
				// Because we use a ViewHolder, we avoid having to call
				// findViewById().
				ProvincesDTOViewHolder viewHolder = (ProvincesDTOViewHolder) convertView
						.getTag();
				imgView = viewHolder.getImgView();
				textView = viewHolder.getTextView();
				textView1 = viewHolder.getTextView1();
			}

			/*
			 * String imgURL = prov.getImgURL(); if (imgURL == null) {
			 */
			imgView.setImageResource(R.drawable.cui_bap);
			
			/*
			 * } else { InputStream is = null; try { is = fetch(imgURL);//
			 * "http://dl.dropbox.com/u/24886653/hinhchoandroid/W128X160PNT065.jpg"
			 * ); } catch (Exception e) {
			 * 
			 * }
			 * 
			 * Drawable drawable = Drawable.createFromStream(is, "src");
			 * 
			 * // Display planet data
			 * 
			 * imgView.setImageDrawable(drawable); }
			 */
			textView.setText(prov.getName());
			textView1.setText(prov.getDescription());
			return convertView;
		}

		private class PTypeFilter extends Filter {

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence prefix,
					FilterResults results) {
				// NOTE: this function is *always* called from the UI thread.
				lstSubItem = (ArrayList<ProvincesDTO>) results.values;

				notifyDataSetChanged();
			}

			@SuppressWarnings("unchecked")
			protected FilterResults performFiltering(CharSequence prefix) {
				// NOTE: this function is *always* called from a background
				// thread, and
				// not the UI thread.

				FilterResults results = new FilterResults();
				ArrayList<ProvincesDTO> i = new ArrayList<ProvincesDTO>();

				if (prefix != null && prefix.toString().length() > 0) {

					for (int index = 0; index < lstAllItem.size(); index++) {
						ProvincesDTO si = lstAllItem.get(index);
						if (si.getName().toLowerCase()
								.contains(prefix.toString().toLowerCase()) == true) {
							i.add(si);
						}
					}
					results.values = i;
					results.count = i.size();
				} else {
					synchronized (lstAllItem) {
						results.values = lstAllItem;
						results.count = lstAllItem.size();
					}
				}

				return results;
			}
		}
	}
}
